package com.example.miaosha.miaosha_20220302.controller;


import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.example.miaosha.miaosha_20220302.entity.Sku;
import com.example.miaosha.miaosha_20220302.service.DetailService;
import com.example.miaosha.miaosha_20220302.service.MiaoshaService;
import com.example.miaosha.miaosha_20220302.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cxw
 * @since 2022-03-02
 */
@RestController
@RequestMapping("/miaosha")
public class MiaoshaController {

    @Autowired
    private SkuService skuService;

    @Autowired
    private DetailService detailService;

    @Autowired
    private MiaoshaService miaoshaService;

    /**
     * 秒杀接口_v1.0.0
     *
     * @param skuId
     * @return
     */
    @RequestMapping("/kill/{skuId}")
    public R doKill_step_one(@PathVariable("skuId") Integer skuId) {
        try{
            checkSku(skuId);
            miaoshaService.doMiaosha(1, skuId);
            return R.restResult("ok", ApiErrorCode.SUCCESS);
        }catch (Exception e){
            return R.failed(e.getMessage());
        }
    }

    private void checkSku(Integer skuId) {
        Sku byId = skuService.getById(skuId);
        if (byId == null) {
            throw new RuntimeException("no skuId record");
        }
        if (byId.getLeavedAmount() < 1) {
            throw new RuntimeException("no left amount!");
        }
    }
}

